package com.rest.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.api.model.ApiService;
import com.api.rest.RestHandler;
import com.api.rest.RestHandlerImpl;
import com.api.rest.model.RestClass;
import com.api.service.ServiceHandler;
import com.api.service.ServiceHandlerImpl;
import com.util.LoadPackage;
import com.zyncro.api.IGroupApiService;

public class ApiRestHandler {

	private final List<Class<?>> apiClasses;

	private final Map<Class<?>, RestClass> classes;
	private final Map<Class<?>, ApiService> services;

	private final String jarName;
	private final String apiVersion;

	public ApiRestHandler() {
		RestHandler restHandler = new RestHandlerImpl();
		ServiceHandler serviceHandler = new ServiceHandlerImpl();

		this.classes = new HashMap<Class<?>, RestClass>();
		this.services = new HashMap<Class<?>, ApiService>();

		this.jarName = IGroupApiService.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		this.apiVersion = jarName.split("zyncro-api-model-")[1].replace(".jar", "");

		apiClasses = LoadPackage.getInterfaces(jarName, "com.zyncro.api");
		for (Class<?> aClass : apiClasses) {

			RestClass restClass = restHandler.getRestClass(aClass);
			this.classes.put(aClass, restClass);

			ApiService apiService = serviceHandler.getApiService(aClass);
			this.services.put(aClass, apiService);
		}
	}

	public List<Class<?>> getApis() {
		return this.apiClasses;
	}

	public RestClass getRestClass(Class<?> aClass) {
		checkApiClass(aClass);
		return this.classes.get(aClass);
	}

	public ApiService getApiService(Class<?> aClass) {
		checkApiClass(aClass);
		return this.services.get(aClass);
	}

	private void checkApiClass(Class<?> aClass) {
		if (aClass == null) {
			throw new IllegalArgumentException("Class cannot be null");
		}
		if (!this.apiClasses.contains(aClass)) {
			throw new IllegalStateException("Api class doesn't exists");
		}
	}

	public String getApiVersion() {
		return this.apiVersion;
	}
}
